package sm.upgrade;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import sm.dam.api.DBDictService;
import sm.upgrade.api.UpgradePhase;

public class SqlsysUpgrade implements UpgradePhase {

	private static Logger logger = LoggerFactory.getLogger(UpgradePhase.class);

	private HibernateTemplate template;

	public void setTemplate(HibernateTemplate template) {
		this.template = template;
	}

	private List<String> oldTables;

	public void setOldTables(List<String> oldTables) {
		this.oldTables = oldTables;
	}

	private boolean isExistInDBDict(String fileName) {
		Object dbdict = template.get(DBDictService.DBDICT, fileName);
		if (dbdict != null) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void upgrade() {
		Map<String, Boolean> remapTables = new HashMap<String, Boolean>();

		logger.info("Checking sqlsystemtables records and remapping tables...");
		List<String> newTables = (List<String>) template
				.find("select dbdict from sqlsystemtables");
		if (oldTables != null && newTables != null) {
			// QCCR1E63576 - only remap the systemperform table, modified by
			// LiuYongliang
			String oldTable = "systemperform";
			if (!newTables.contains(oldTable)) {
				remapTables.put(oldTable, true);
			}

			// QCCR1E63576 - skip the code and ScriptLibrary table, modified by
			// LiuYongliang
			for (String newTable : newTables) {
				// filter upgrade tables
				if (!oldTables.contains(newTable) && !"code".equals(newTable)
						&& !"ScriptLibrary".equals(newTable)
						&& !newTable.startsWith("upgrade")) {
					remapTables.put(newTable, false);
				}
			}
		}
		logger.info("  Finished checking sqlsystemtables records and remapping tables.");

		for (Entry<String, Boolean> entry : remapTables.entrySet()) {
			String fileName = entry.getKey();
			Object dbdict = template.get(DBDictService.DBDICT, fileName);
			if (dbdict != null) {
				boolean dir = entry.getValue();
				if (logger.isDebugEnabled()) {
					if (dir) {
						logger.debug("Remap table {} from BLOB to nonBLOB",
								fileName);
					} else {
						logger.debug("Remap table {} from nonBLOB to BLOB",
								fileName);
					}
				}
			}
		}
	}
}
